<?php
/**
 * CreateAdminForm class.
 * It is used by action 'user/install/createAdmin' and user/backend/user/create only.
 */
class CreateUserForm extends CFormModel
{
	public $first_name;
	public $last_name;
	public $name;
	public $name_option; // 0: first_name + last_name; 1: last_name + first_name
	public $email;
	public $password;
	public $group_id;
	public $sendWelcomeEmail;
	public $term;
	
	public function rules()
	{
		return array(
			array('first_name, last_name, email', 'required'),
			array('name_option, password', 'required', 'on'=>'create'), // must be set when user is being created by admin
			array('term','agreeTerm', 'on'=>'register'), // guest must agree
			array('name_option, sendWelcomeEmail', 'numerical', 'integerOnly'=>true),
			array('name','generate'),
			array('email','email'),
			array('email','unique','className'=>'User'),
			array('group_id', 'exist', 'className'=>'UserGroup', 'attributeName'=>'id'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'name'			=> Yii::t('user','Họ và tên'),
			'name_option'	=> Yii::t('user','Họ và tên'),
			'first_name'	=> Yii::t('user','Họ'),
			'last_name'		=> Yii::t('user','Tên'),
			'email'			=> Yii::t('user','Địa chỉ email'),
			'password'		=> Yii::t('user','Mật khẩu'),
			'group_id'		=> Yii::t('user','Nhóm thành viên'),
			'sendWelcomeEmail'=> Yii::t('user','Gửi email chào mừng'),
			'term'			=> Yii::t('user','Tôi đồng ý điều khoản!'),
		);
	}
	
	public function agreeTerm($attribute, $params)
	{
		if((int)$this->term==0)
		{
			$this->addError($attribute, Yii::t('user','Bạn phải đồng ý với điều khoản!'));
		}
	}

	public function generate($attribute, $params)
	{
		if( ! $this->hasErrors())
		{
			if($this->name_option == 1)
				$this->name = $this->last_name . ' ' . $this->first_name;
			else
				$this->name = $this->first_name . ' ' . $this->last_name;
			
		}
	}

}
